﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharePointHNSC.Timerjob
{
    public class ApplyApplicationContentToAllServerTimerJob : SPJobDefinition
    {

        internal static string TIMERJOB_NAME = "ApplyApplicationContentToAllServer";

        public override string Description
        {
            get
            {
                return "Apply Application Content To All Server TimerJob";
            }
        }

        public override string DisplayName
        {
            get
            {
                return "Apply Application Content To All Server TimerJob";
            }
        }

        public ApplyApplicationContentToAllServerTimerJob() : base() { }

        public ApplyApplicationContentToAllServerTimerJob(string name, SPService service)
            : base(name, service, null, SPJobLockType.None)
        {
            this.Title = name;
            this.Schedule = new SPOneTimeSchedule(DateTime.Now);
        }

        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication administrationWebApplication = SPAdministrationWebApplication.Local;

            string source = SPUtility.GetCurrentGenericSetupPath("CONFIG\\AdminResources");
            if (Directory.Exists(source))
            {
                foreach (SPUrlZone zone in administrationWebApplication.IisSettings.Keys)
                {
                    string destination = administrationWebApplication.GetIisSettingsWithFallback(zone).Path + "\\App_GlobalResources";

                    if (Directory.Exists(destination))
                    {
                        string[] resourceFiles = Directory.GetFiles(source, "SharePointHNSC.spadmin.*");
                        foreach (string filename in resourceFiles)
                        {
                            string destinationFilename = destination + "\\" + Path.GetFileName(filename);
                            File.Copy(filename, destinationFilename, true);
                        }
                    }
                }
            }
        }
    }
}